require 'cgi'
require 'kconv'
class Hash
  def to_nested_param(parts = [], parameters = [], encode = nil)
    self.each do |key, value|
      key = key.to_s
      case value
      when Hash
        if parts.empty?
          parts.push CGI.escape(key)
        else
          parts.push "[#{CGI.escape(key)}]"
        end
        value.to_nested_param(parts, parameters, encode)
        parts.pop
      when Array
        parts.push parts.empty? ? CGI.escape(key) : "[#{CGI.escape(key)}]"
        value.each do |v|
          v = (v || '').to_s
          v = v.kconv(encode, Kconv::UTF8) unless encode.nil?
          parameters.push "#{parts.join('')}[]=#{CGI.escape(v)}"
        end
        parts.pop
      else
        parts.push parts.empty? ? CGI.escape(key) : "[#{CGI.escape(key)}]"
        value = (value || '').to_s
        value = value.kconv(encode, Kconv::UTF8) unless encode.nil?
        parameters.push "#{parts.join('')}=#{CGI.escape(value)}"
        parts.pop
      end
    end
    parameters.join('&')
  end

  def to_hidden_field_tag
    fields = []
    self.to_nested_param.split(/&/).each do |query|
      parts = query.split(/=/)
      fields << "<input type=\"hidden\" name=\"#{parts[0]}\" value=\"#{CGI.escapeHTML CGI.unescape(parts[1] || '')}\" />"
    end
    fields.join("\n")
  end
end
